#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
   @Author: 即将拥有人鱼线的yjw
   @Time: 2023/12/17 18:23
   @File: bladeUpdate.py
   @desc:
"""
import json
import os
import sys

import requests
import xlrd

headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0',
        'Connection': 'keep-alive',
        'Content-Type': 'application/json'
}

userList = {
            'sunjj25767': 'wDsTRTkM9GUKqHI9HXx7W6kbeWSa3Iqidu_eI6banLS5DG7y6e78mx2AvYtnMp9NY-koHnquZ4CB0Z2sRUjIrw',
            'chenwq28514': 'wDsTRTkM9GUKqHI9HXx7W6kbeWSa3Iqidu_eI6banLT5hW9y4gk5wd3sGn7kNWrUY2-tFzJOb2aTaRv8rJaSHw',
            'dujq47197': 'wDsTRTkM9GUKqHI9HXx7W6kbeWSa3Iqidu_eI6banLSVpSxOP55X8RaCtyBWHGax8n6cPWC7s5WqLnX-YinyFA',
            'gansc21420': 'wDsTRTkM9GUKqHI9HXx7W6kbeWSa3Iqidu_eI6banLRGj6UxSXQDMzrGqp-xaV-PBjpHXc3EPZ4Y5AteSqnblQ',
            'huzh32405': 'wDsTRTkM9GUKqHI9HXx7W6kbeWSa3Iqidu_eI6banLRtnLTGVt_TDj-GMwoYoV6NRI3VZYNgBrv9MbHocjje9g',
            'lijl31833': 'wDsTRTkM9GUKqHI9HXx7W6kbeWSa3Iqidu_eI6banLQ92B0JwGK04RM9aOq2aVfYgoU7aFm3CuV33ujJEs0vCg',
            'zhangxl29470': 'wDsTRTkM9GUKqHI9HXx7W6kbeWSa3Iqidu_eI6banLQZqLnDUK52pa8hGpiycGLKOi0u4_spUCjQPdL1JyiNUg',
            'zhangyuan20788': 'wDsTRTkM9GUKqHI9HXx7W6kbeWSa3Iqidu_eI6banLQ6z7DBLKmMnwHd1-qYOkhOrRlm_RTsvWkADYwdX2EhuQ',
            'yejw46507':'wDsTRTkM9GUKqHI9HXx7W6kbeWSa3Iqidu_eI6banLSOUmO6bsoeaHWvxeNmpY7n-Yr4cHnJJWwjDn_wnoN_YQ',
            'liys50378':'wDsTRTkM9GUKqHI9HXx7W6kbeWSa3Iqidu_eI6banLQMIsvvjMNoAahhjNhMhUtb9uLvEUML4mzyqnuwHvN3fA'

}
class OperationExcel:
    def __init__(self,xlsxName,sheetName):
        self.sheetName = sheetName
        self.xlsxName = xlsxName

    def getSheet(self):
        path = getFilePath(self.xlsxName+'.xlsx')
        # logger.info(f'用例路径：{path}')
        book = xlrd.open_workbook(path)
        return book.sheet_by_name(self.sheetName)#

    def getSheets(self):
        path = getFilePath(self.xlsxName+'.xlsx')
        # logger.info(f'用例路径：{path}')
        book = xlrd.open_workbook(path)
        return book._sheet_names#

    def getExcelDatas(self):
        data = []
        title = self.getSheet().row_values(0)#获取表头
        for row in range(1,self.getSheet().nrows):
            row_value = self.getSheet().row_values(row)
            data.append(dict(zip(title,row_value)))
        return data




#对excel表头进行全局变量定义
class ExcelVarles:
    case_name = '测试用例'
    case_data = '请求参数'
    case_type = '用例类型'
    case_result = '期望结果'
    case_before = '前置条件'
    case_describe = '步骤描述'
    case_path = '路径'

def getExcelData(xlsxName,sheetName,caseName):
    '''
    获取EXCEL用例数据
    '''
    data = []
    data1 = OperationExcel(xlsxName, sheetName).getExcelDatas()
    if data1:
        for i in data1:
            if caseName in i.values():
                data.append(i)
        return data
    else:
        return []

def getFilePath(fileName,path='F:\data'):
    print(fileName)
    # path = 'E:\执行机系列对外\执行机系列对外\data\合规5.0\合规5.0\标准数据\自动化\QturboPythonScript\合规5.0\web应用\data'
    '''
    读取文件
    '''
    fileName = fileName.strip()
    if '\\' in fileName:
        return fileName
    else:
        if '执行机系列对外' in fileName:
            return fileName
        else:
            for root,dirs,files in os.walk(path):
                for file in files:
                    # 获取文件所属目录
                    # print(root)
                    # 获取文件路径
                    file = os.path.join(root, file)
                    print(os.path.join(root, file))
                    if fileName in file:
                        #logger.info(f'文件路径：{file}')
                        return file

def bladeUpload(user,nodePath,excelName,sheetName,caseName,stepDes,inputData,expect,case_before):
    # user = 'yejw46507'
    # user_key = 'wDsTRTkM9GUKqHI9HXx7W6kbeWSa3Iqidu_eI6banLSOUmO6bsoeaHWvxeNmpY7n-Yr4cHnJJWwjDn_wnoN_YQ'

    TEMPLATEDATA = {
        "api_token": userList.get(user),  # blade授权码
        "account": user,  # 授权码用户
        "vid": "",
        "vName": "",
        "nodePath": nodePath,  # 路径
        "data": [{
            "caseName": caseName,  # 案例名
            "caseType": "2",  # 案例类型 1-手工,2-自动化
            "casePrior": "P1",  # 优先级P0-3
            "caseSideType": "0",  # 正例 or 反例
            "caseDetailType": "0",  # 用例类型 0-功能,1-性能,2-文档,3-安全,4-兼容性,5-可靠性,6-用户体验,7-安装部署
            "caseLayer": "1",  # 用例分层 0-系统级,1-模块级
            "caseHeader": user,  # 用例责任人
            "caseReviewStatus": "0",
            "caseReviewBy": user,  # 用例审核人
            "caseKeyword": "",
            "accurateWord": "",
            "caseDesc": "",  # 用例描述
            "testPointName": "",  # 测分
            "reqNum": "",  # 需求
            "taskNum": "",  # 任务
            "modifyNum": "",  # 修改单
            "step": [{
                "stepName": "",  # 步骤名称
                "stepJson": {
                    "stepDes": stepDes,  # 步骤描述
                    "inputData": inputData.replace('%','%25'),  # 输入数据
                    "Expect": expect.replace('%','%25'),  # 预期结果
                    "precisionTest": "0",
                    # "user_key_f6342dfec9cc4d70b53f876": "",  # 前置条件*
                    'user_key_81cb6a91bfa1ed44fd8fecb':case_before,
                    "user_key_operator": "",
                    "preSqlContent": [{
                        "id": "",
                        "type": "",
                        "content": "",
                        "connection": "",
                    }],
                    "scriptContent": "c647c4b6c79040a8bce4c723439ebcc4",  # 脚本ID
                    "scriptPath": "",  # 脚本路径
                    "dataContent": {  # 数据参数
                        "id": "",
                        "dataChoseRow": "",
                        "content": "",
                        "dataArrContent": [{
                            "Sheet1": [
                                ["1", "序号", "期望", 'excelName', 'sheetName', 'caseName'],
                                ["2", "参数说明", "", "", "", ""],
                                ["3", "", "flage=true", excelName, sheetName, caseName]
                            ],
                        }],
                    },
                    "checkContent": [{
                        "checkConnection": "",
                        "DBExpect": "",
                        "DBCheckSQL": "",
                        "DBSqlId": "",
                        "DBSqlName": "",
                    }],
                    "stepExcute": "是",
                },
            }],
            "caseState": "1",  # 0-待设计,1-审核通过,2-审核不通过,3-免审核,4-未提交待审核
        }],
    }
    url='http://cloud.blade.hundsun.com/shareInterface/importOfflineCase.json'
    res = requests.post(url, json.dumps(TEMPLATEDATA), headers)
    res_data = res.json()
    print(res_data)


def run():
    exe_dir = os.path.dirname(sys.argv[0])
    # f_path=f'{os.getcwd()}\config.txt'
    f_path = f'{exe_dir}\config.txt'
    print(f_path)
    user = ''
    xlsxName = ''
    with open(f_path, 'r', encoding='utf-8') as f:
        line = f.readline()
        while line:
            if 'user' in line:
                user = line.split('=')[1].strip()
            if 'xlsxName' in line:
                xlsxName = line.split('=')[1].strip()
            if 'path' in line:
                path = line.split('=')[1].strip()
            print(line)
            line = f.readline()

    sheetNames = OperationExcel(xlsxName, 'sheetName').getSheets()
    print(sheetNames)
    for sheetName in sheetNames:
        datas = OperationExcel(xlsxName, sheetName).getExcelDatas()
        path = datas[0][ExcelVarles.case_path]
        nodePath = path + '/查询控件'
        print(nodePath)
        for data in datas:
            print(data)
            caseName = data[ExcelVarles.case_name]
            stepDes = data[ExcelVarles.case_describe]
            inputData = data[ExcelVarles.case_data]
            expect = data[ExcelVarles.case_result]
            case_before = data[ExcelVarles.case_before]
            bladeUpload(user, nodePath, xlsxName, sheetName, caseName, stepDes, inputData, expect, case_before)

if __name__ == '__main__':
    run()
    # nodePath = '/用例转化-模板/风险项预警查询/查询/查询控件'
    # xlsxName = '统计中心-信用业务-融资融券'
    # sheetName ='维保比例盯盘'

    #     bladeUpload(nodePath,xlsxName, sheetName, caseName, stepDes, inputData, expect,case_before)